package com.wjx.source;

import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.Set;

import java.util.TreeSet;

public class SourcePath {
	private boolean first = true;
	private String root;
	
	private Set<String> sourcePaths = new TreeSet<String>();
	public Set<String> disposeDirectory(File rootFile) {
		if(rootFile.getPath().equals("")){
			rootFile=rootFile.getAbsoluteFile();
		}
		if (!rootFile.exists()) {
			return null;
		}
		if (first) {
			this.root=rootFile.getAbsolutePath().replaceAll("\\\\", "\\\\\\\\");
			first = false;
		}
		File[] files =rootFile.listFiles(filter);
		
		for (File file : files) {
			if (file.isDirectory()) {
				sourcePaths=disposeDirectory(file);
			} else {
				String sourcePath=disposeFile(file);
				sourcePaths.add(sourcePath);
			}
		}
		
		return sourcePaths;
	}
	private FilenameFilter filter = new FilenameFilter() {

		public boolean accept(File dir, String name) {
			boolean result = false;
			if (dir.isDirectory()) {
				if (name.endsWith(".java") || !name.contains("."))
					result = true;
			} else {
				if (name.endsWith(".java"))
					result = true;
			}
			;
			return result;
		}
	};
	private String disposeFile(File file) {
		String removeRootedAbsolutePath = file.getAbsolutePath().replaceAll(root,"");
		String packageString = getPackageString(file);
		String packageStringAndFileName;
		if(removeRootedAbsolutePath.contains(packageString)){
			packageStringAndFileName = packageString+File.separator+file.getName();
		}else{
			packageStringAndFileName = file.getName();
		}
		
		String replacedPackageStringAndFileName=packageStringAndFileName.replace("\\", "\\\\");
		
		removeRootedAbsolutePath=removeRootedAbsolutePath.replaceAll(replacedPackageStringAndFileName,"");
		removeRootedAbsolutePath=removeRootedAbsolutePath.replaceAll("\\\\", "/").replaceFirst("/", "");
		if(removeRootedAbsolutePath.endsWith("/"))
		removeRootedAbsolutePath=removeRootedAbsolutePath.substring(0, removeRootedAbsolutePath.length()-1);
		return removeRootedAbsolutePath;
	}
	private String getPackageString(File javaFile) {
		String read = null;
		try {
			LineNumberReader reader = new LineNumberReader(new InputStreamReader(new FileInputStream(javaFile)));
			while ((read = reader.readLine()) != null&& !read.contains("package"));
			
			if (read != null) {
				read=read.substring(read.indexOf("package"));
				read = read.replaceFirst("package", "").trim().replace(";", "").replace(".", "\\");
			}
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return read!=null?read:"";
	}
}
